from flask import request
from sqlalchemy import or_
from flask_jwt_extended import jwt_required, create_access_token
from . import app
from .models import User, db


@app.route("/user/register", methods=["POST"])
def register():
    """
    用户信息注册
    :return:
    """
    try:
        data = request.json
        if not data.get("name"):
            return {"code": 1001, "msg": "注册失败！请输入用户名"}, 400
        if not data.get("mobile"):
            return {"code": 1001, "msg": "注册失败！请输入手机号"}, 400
        if User.query.filter(User.name == data.get("name", None)).first():
            return {"code": 1001, "msg": "注册失败！用户名已注册"}, 400
        elif User.query.filter(User.mobile == data.get("mobile", None)).first():
            return {"code": 1001, "msg": "注册失败！手机号已注册"}, 400
        else:
            # 创建用户数据
            user = User(**data)
            db.session.add(user)
            db.session.commit()
            return {"code": 0, "msg": "注册成功！", "data": {"id": user.id, "name": user.name}}, 200
    except Exception as e:
        print(e)
        return {"code": 1001, "msg": "注册失败！参数有误", "data": {}}, 400


@app.route("/user/login", methods=["POST"])
def login():
    """
    用户登录
    :return:
    """
    if request.json.get("name"):
        user = User.query.filter(
            or_(
                User.mobile == request.json.get("name"),
                User.name == request.json.get("name"),
            )
        ).first()  # 实例化模型
        if not user:
            return {"code": 1001, "msg": "登录失败！用户不存在！", "data": {}}, 400

        if not user.check_password(request.json.get("password")):
            return {"code": 1001, "msg": "登录失败！密码错误！", "data": {}}, 400
        # 生成token，并返回给客户端
        access_token = create_access_token(identity={"id": user.id, "username": user.name})
        return {"code": 0, "msg": "登录成功", "data": {"id": user.id, "name": user.name, "token": access_token}}, 200
    else:
        return {"code": 1001, "msg": "登录失败！用户为空！", "data": {}}, 400


@app.route('/user/index', methods=["GET"])
@jwt_required()
def index():
    return {"msg": "访问成功"}


@app.route('/user/delete', methods=["DELETE"])
def drop_table():
    db.drop_all()
    return {"msg": "删除表成功"}


@app.route('/user/create', methods=["GET"])
def create_table():
    db.create_all()
    return {"msg": "创建表成功"}
